package com.cq.androidtools.text

import java.io.File
import java.nio.charset.Charset
import javax.xml.parsers.DocumentBuilderFactory

/**
 * 作者: CQ
 * 日期: 2022-07-11
 * 说明:
 */
fun main() {
    //    val file = File("E:\\0.xhtml").readLines().forEach {
    //        println(it)
    //    }
    val dbf = DocumentBuilderFactory.newInstance()
    val documentBuilder = dbf?.newDocumentBuilder()
    val document = documentBuilder?.parse(File("E:\\0.xhtml"))
    val title = document?.documentElement?.getElementsByTagName("title")
    println(title!!.item(0).firstChild.nodeValue)
    val items = document.documentElement?.getElementsByTagName("p")
    for (i in 0 until items?.length!!) {
        println(items.item(i).firstChild.nodeValue)
    }
}

fun Any.getDataXS() : String {
    val path = android.os.Environment.getExternalStorageDirectory().absolutePath + "/BAISON/0.xhtml"

    val dbf = DocumentBuilderFactory.newInstance()
    val documentBuilder = dbf?.newDocumentBuilder()
    val document = documentBuilder?.parse(File(path))
    val title = document?.documentElement?.getElementsByTagName("title")
    println(title!!.item(0).firstChild.nodeValue)
    val items = document.documentElement?.getElementsByTagName("p")
    val stringBuilder = StringBuilder()
    for (i in 0 until items?.length!!) {
        stringBuilder.append("\u3000\u3000").append(items.item(i).firstChild.nodeValue).append("\n")
    }
    return stringBuilder.toString()
}

/**
 * 自动换行，最后一行不换行
 */
fun onAutoWrap(str : String, sub : Int) : String {
    var str_1 = ""
    val s = str.toCharArray()
    val end = java.lang.StringBuilder()
    for (i in s.indices) {
        if (getBytesLength(str_1) + getBytesLength(s[i].toString()) >= sub) {
            end.append(str_1)
            str_1 = ""
            if (i < s.size - 1) {
                end.append("\n")
            }
        }
        str_1 += s[i]
        if (i == s.size - 1) {
            end.append(str_1)
        }
    }
    return end.toString()
}

fun getBytesLength(msg : String) : Int {
    return msg.toByteArray(Charset.forName("GB2312")).size
}